/*
 * Copyright (C) 2020 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.jc.camerascan.fragment.mine;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jc.camerascan.R;
import com.jc.camerascan.activity.mine.UserCenterActivity;
import com.jc.camerascan.activity.webview.WebviewActivity;
import com.jc.camerascan.core.BaseFragment;
import com.jc.camerascan.core.http.bean.CustomApiResult;
import com.jc.camerascan.core.http.callback.TipCallBack;
import com.jc.camerascan.entity.mine.GetUserInfoResult;
import com.jc.camerascan.entity.mine.MyMenu;
import com.jc.camerascan.login.LoginActivity;
import com.jc.camerascan.utils.AppMarketUtils;
import com.jc.camerascan.utils.ImageUtil;
import com.jc.camerascan.utils.JurisdictionUtils;
import com.jc.camerascan.utils.MMKVUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.imageview.RadiusImageView;
import com.xuexiang.xui.widget.layout.XUIRelativeLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.app.ActivityUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Package: com.jc.camerascan.fragment.mine
 * @Description: java类作用描述
 * @Author: xuchi
 * @CreateDate: 2020/7/30 1:23
 * @Version: 1.0
 */
public class MineFragment extends BaseFragment {

    @BindView(R.id.menuView)
    LinearLayout menuView;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.head_img)
    RadiusImageView headImg;
    @BindView(R.id.tips)
    TextView tips;
    @BindView(R.id.tips_layout)
    XUIRelativeLayout tipsLayout;
    @BindView(R.id.btn_text)
    SuperButton btnText;
    @BindView(R.id.head_layout)
    ConstraintLayout headLayout;

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        return null;
    }

    /**
     * 布局的资源id
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        initMineMenu();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if ((isVisibleToUser && isResumed())) {
            // TODO  可见操作
            initInfo();
        } else if (!isVisibleToUser) {
            // TODO  不可见操作
        }
    }

    // Fragment页面onResume函数重载
    public void onResume() {
        super.onResume();
        initInfo();
    }

    private void initInfo() {
        if (JurisdictionUtils.isLogin()) {
            getUserInfo();
        } else {
            name.setText("未登录");
            tips.setText("点击头像进行登录");
            btnText.setVisibility(View.GONE);
        }
    }

    private void getUserInfo() {
        XHttp.get("/api/User/GetInfo")
                .execute(new CallBackProxy<CustomApiResult<GetUserInfoResult>, GetUserInfoResult>(new TipCallBack<GetUserInfoResult>() {
                    @Override
                    public void onSuccess(GetUserInfoResult response) throws Throwable {
                        name.setText(response.getNickname());
                        MMKVUtils.put("is_vip", response.getIs_vip());
                        if (response.getIs_vip() == 0) {
                            tips.setText(response.getVip_desc());
                            btnText.setText("开通会员");
                        } else {
                            tips.setText(response.getVip_desc());
                            btnText.setText("续  费");
                        }
                        ImageUtil.loadBlurImage(getActivity(), response.getHeadimgurl(), headImg);
                        btnText.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        name.setText("未登录");
                        tips.setText("点击头像进行登录");
                        btnText.setVisibility(View.GONE);
                    }
                }) {
                });
    }

    private void initMineMenu() {
        XHttp.get("/api/Home/GetMyMenuList")
                .execute(new CallBackProxy<CustomApiResult<List<MyMenu>>, List<MyMenu>>(new TipCallBack<List<MyMenu>>() {
                    @Override
                    public void onSuccess(List<MyMenu> response) throws Throwable {
                        initMenu(response);
                    }
                }) {
                });
    }

    private void initMenu(List<MyMenu> response) {
        if (response != null && !response.isEmpty()) {
            for (MyMenu myMenu : response) {
                View item = LayoutInflater.from(getActivity()).inflate(R.layout.menu_view, null);
                SuperTextView menuItem = item.findViewById(R.id.menu_item);
                menuItem.setLeftString(myMenu.getTitle());

                if (myMenu.getUrl().contains("SBJL")) {
                    menuItem.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
                        @Override
                        public void onClick(SuperTextView superTextView) {
                        }
                    });
                } else if (myMenu.getUrl().contains("GGHP")) {
                    menuItem.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
                        @Override
                        public void onClick(SuperTextView superTextView) {
                        }
                    });
                } else if (myMenu.getUrl().contains("Exit")) {
                    menuItem.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
                        @Override
                        public void onClick(SuperTextView superTextView) {
                            new MaterialDialog.Builder(getContext())
                                    .title("退出登录")
                                    .content("确定要退出登录么？")
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            MMKVUtils.put("is_login", false);
                                            MMKVUtils.put("is_vip", 0);
                                            MMKVUtils.put("xc_access_token", "");
                                            //设置你的操作事项
                                            dialog.dismiss();
                                            LoginActivity.start(getActivity());
                                            getActivity().finish();
                                        }
                                    })
                                    .show();
                        }
                    });
                } else if (myMenu.getUrl().contains("Exit")) {
                    menuItem.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
                        @Override
                        public void onClick(SuperTextView superTextView) {
                            AppMarketUtils.gotoMarket(getActivity());
                        }
                    });
                }else {
                    menuItem.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
                        @Override
                        public void onClick(SuperTextView superTextView) {
                            Intent intentActivityWebview1 = new Intent();
                            intentActivityWebview1.setClass(getContext(), WebviewActivity.class);
                            intentActivityWebview1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intentActivityWebview1.putExtra("url", myMenu.getUrl());
                            intentActivityWebview1.putExtra("title", myMenu.getTitle());
                            startActivity(intentActivityWebview1);
                        }
                    });
                }

                RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.ic_launcher)
                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                Glide.with(this)
                        .load(myMenu.getIcon())
                        .apply(options)
                        .into(menuItem.getLeftIconIV());
                menuView.addView(item);
            }
        }

    }

    @OnClick(R.id.head_img)
    public void onHeadImgClicked() {
        if (!JurisdictionUtils.isLogin()) {
            ActivityUtils.startActivity(LoginActivity.class);
        }
    }

    @OnClick(R.id.btn_text)
    public void onBtnTextClicked() {
        UserCenterActivity.start(getActivity());
    }
}
